package com.hudage.kotlinmvp.mvp.presenter

import com.hudage.kotlinmvp.base.BasePresenter
import com.hudage.kotlinmvp.mvp.contract.DiscoveryDetailContract
import com.hudage.kotlinmvp.mvp.model.DiscoveryDetailModel
import com.orhanobut.logger.Logger

class DiscoveryDetailPresenter : BasePresenter<DiscoveryDetailContract.View>(),
    DiscoveryDetailContract.Presenter {
    private val discoveryDetailModel by lazy {
        DiscoveryDetailModel()
    }

    private var nextPageUrl: String? = null

    /**
     * 获取分类详情的列表信息
     */
    override fun getCategoryDetailList(id: Long) {
        checkViewAttached()
        val disposable = discoveryDetailModel.getDiscoveryDetailData(id)
            .subscribe({ issue ->
                mRootView?.apply {
                    nextPageUrl = issue.nextPageUrl
                    setCateDetailList(issue.itemList)
                }
            }, { throwable ->
                Logger.d(throwable.toString())
                mRootView?.apply {
                    showError(throwable.toString())
                }
            })

        addSubscription(disposable)
    }

    /**
     * 加载更多数据
     */
    override fun loadMoreData() {
        val disposable = nextPageUrl?.let {
            discoveryDetailModel.getMoreData(it)
                .subscribe({ issue ->
                    mRootView?.apply {
                        nextPageUrl = issue.nextPageUrl
                        setCateDetailList(issue.itemList)
                    }
                }, { throwable ->
                    mRootView?.apply {
                        showError(throwable.toString())
                    }
                })
        }

        disposable?.let { addSubscription(it) }
    }
}